package com.zlp.springcloud.rule;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: zhulaiping
 * @Date: 2021/7/13 13:54
 */
@Component
public class MyLb implements LoadBalancer{
    private AtomicInteger cnt = new AtomicInteger();

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int cur = 0,next = 0;
        do {
            cur = cnt.get();
            next = cur+1==Integer.MAX_VALUE?0:cur+1;
        }while (!cnt.compareAndSet(cur,next));
        System.out.println(next);
        return serviceInstances.get(next%serviceInstances.size());
    }
}
